package com.e3roid.examples;

import android.view.MotionEvent;
import android.widget.Toast;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.sprite.TextSprite;
import com.e3roid.script.javascript.JavaScriptEngine;

/**
 * Example of Scripting with JavaScript.
 *
 */
public class ScriptingJavaScriptExample extends E3Activity {

	private final static int WIDTH  = 320;
	private final static int HEIGHT = 480;

	private JavaScriptEngine jsEngine;
	private TextSprite label1;
	private TextSprite label2;

	@Override
	public E3Engine onLoadEngine() {
		E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);
		engine.requestFullScreen();
		engine.requestPortrait();
		return engine;
	}

	@Override
	public E3Scene onLoadScene() {
		E3Scene scene = new E3Scene();
		scene.addEventListener(this);
		
		// Move the label to center of the screen.
		label1.move((getWidth() - label1.getWidth()) / 2, (getHeight() - label1.getHeight()) / 2);
		label2.move((getWidth() - label2.getWidth()) / 2, (getHeight() - label2.getHeight()) / 2 + (label1.getHeight() * 2));
		
		label1.useDefaultRotationAndScaleCenter();
		
		scene.getTopLayer().add(label1);
		scene.getTopLayer().add(label2);
		
		Toast.makeText(this, "Touch screen to count up.", Toast.LENGTH_LONG).show();
		
		return scene;
	}

	/**
	 * Create label with value from JavaScript script.
	 */
	@Override
	public void onLoadResources() {
		jsEngine = JavaScriptEngine.loadFromAsset("hello.js", this);
		String helloFromJavaScript = jsEngine.call("hello", "Hello", "World");
		
		// Create new Label instance with parameters fontSize=18
		label1 = new TextSprite(helloFromJavaScript, 18, this);
		label2 = new TextSprite("count = XX", 18, this);
		label2.hide();
	}

	/**
	 * Count up and rotate the label from script.
	 */
	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
		if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
			
			Double count = jsEngine.call("countup");
			label2.setText(String.format("count = %d", (int)count.doubleValue()));
			
			if (!label2.isVisible()) {
				label2.show();
			}
			
			jsEngine.call("rotate", label1);
		}
		return false;
	}
}